import React from "react";
import { useNavigate } from "react-router-dom"
import { doLogin } from "@services/user";
import { ToastContainer } from 'react-toastify'
import { setToken } from "@utils/authenticator"

const Login = () => {
  const navigate = useNavigate()
  const onSubmit = async (e) => {
    e.preventDefault()
    const name = document.getElementById('name').value;
    const pwd = document.getElementById('pwd').value;
    const data = {
      name,
      pwd
    }
    const res = await doLogin(data)
    if (res && res.code === '000000') {
      setToken(res?.data?.token)
      navigate('/root/home')
    }
  }
  const handleGotoResister = () => {
    navigate('/register')
  }
  return (
    <div className="p-5 w-80 mt-8 mx-auto rounded-md bg-white shadow-md">
      <h2 className="text-2xl my-5 font-bold">登录</h2>
      <form id="loginForm" onSubmit={onSubmit}>
        <div className="mb-5">
          <label className="block">用户名:&nbsp;&nbsp;&nbsp;&nbsp;</label>
          <input autoComplete="off" className="rounded-[5px] border-[1px] border-[#ccc] border-solid p-2.5 w-full bg-white" type="text" id="name" name="name" required />
        </div>
        <div className="mb-5">
          <label className="block">密&nbsp;&nbsp;&nbsp;&nbsp;码:&nbsp;&nbsp;&nbsp;&nbsp;</label>
          <input autoComplete="off" className="rounded-[5px] border-[1px] border-[#ccc] border-solid p-2.5 w-full bg-white" type="password" id="pwd" name="pwd" required />
        </div>
        <button type="submit" className="w-full bg-[#007BFF] hover:bg-[#0056b3] text-white p-2.5 rounded-[5px] cursor-pointer">
          登录
        </button>&nbsp;&nbsp;&nbsp;&nbsp;
        <button onClick={handleGotoResister}>注册</button>
      </form>
      <ToastContainer autoClose={5000} />
    </div>
  )
}

export default Login